import React, { Component } from 'react';
import ReactEcharts from 'echarts-for-react';

import styles from '../style.less';

require('@/utils/theme/macarons');

interface PropType {
  [propName: string]: any;
}

interface StateType {
  [propName: string]: any;
}

function getChartData(data: { today: any[] }) {
  let xData: string[] = [];
  let yData: string[] = [];
  const { today } = data;
  if (today) {
    xData = Object.keys(today);
    yData = xData.map(item => today[item]);
  }
  return { xData, yData };
}

class DisplayChart extends Component<PropType, StateType> {
  public state = {
    animationDuration: 1000,
  };

  public chartRef: any;

  getOption = (xData: any[], yData: any[]) => {
    const series = [
      {
        name: '',
        type: 'line',
        stack: 'vistors',
        barWidth: '60%',
        data: yData,
        animationDuration: this.state.animationDuration,
      },
    ];

    const options = {
      tooltip: {
        trigger: 'axis',
      },
      calculable: true,
      dataZoom: [
        {
          type: 'inside',
          show: true,
          realtime: true,
          start: 0,
          end: 100,
        },
        {
          type: 'slider',
        },
      ],
      xAxis: [
        {
          type: 'category',
          boundaryGap: false,
          data: xData,
        },
      ],
      yAxis: [
        {
          type: 'value',
        },
      ],
      series,
    };
    return options;
  };

  render() {
    const { data } = this.props;
    const { xData, yData } = data ? getChartData(data) : { xData: [], yData: [] };

    return (
      <div className={styles.chart} ref={() => this.chartRef}>
        <ReactEcharts option={this.getOption(xData, yData)} notMerge lazyUpdate theme="macarons" />
      </div>
    );
  }
}

export default DisplayChart;
